package com.lanswon.qzsmk.controller.cardManageController;


import java.io.File;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.ServiceUI;
import javax.print.SimpleDoc;
import javax.print.attribute.DocAttributeSet;
import javax.print.attribute.HashDocAttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.swing.JFileChooser;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import ch.qos.logback.classic.Logger;

import com.lanswon.qzsmk.base.PathContants;
import com.lanswon.qzsmk.exception.SystemException;
import com.lanswon.qzsmk.model.Cert;
import com.lanswon.qzsmk.util.pdfutil.PDF2Image;
import com.lanswon.qzsmk.util.pdfutil.PrintPDFImage;
import com.lanswon.qzsmk.util.pdfutil.RemoteFile;
import com.lanswon.qzsmk.util.pdfutil.TempletTicket;
import com.lanswon.qzsmk.vo.VoucherVo;

/**
 * 描述：打印各业务凭控制器
 * 创建日期：20180126
 * 版本：v1.0
 * @author 惠国磊
 *
 */

@Controller
@RequestMapping(value="/printCredentials")
public class CredentialsPrintController {
	/*logger对象*/
	private final static Logger logger = (Logger) LoggerFactory.getLogger(CredentialsPrintController.class);
	/*通用map*/
//	private Map<String,Object> workMap = new HashMap<String,Object>();
	
	/**
	 * 预览请求
	 * @param request
	 * @return map
	 */
	@RequestMapping(value="/toPdfView",method=RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> pdfEdit(HttpServletRequest request){
		
		logger.info("pdfEdit########start()");
		String cardNo = request.getParameter("cardNo");
		String credential_type = request.getParameter("applyType");
		String bussinessType = null;
		Map<String,Object> workMap = new HashMap<String,Object>();
		
		try {
			bussinessType = URLDecoder.decode(request.getParameter("bussinessType"),"utf-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
			
			String msg="转码异常";
			logger.error(msg);
			throw new SystemException(SystemException.UnsupportedEncodingException, msg);

		}
		String cardType = request.getParameter("cardType");
		String branchNo = request.getParameter("branchNo");
		String opeatorNo = request.getParameter("opeatorNo");
		String cardAppointmentMiles = request.getParameter("cardAppointment");
		Date date = new Date(Long.parseLong(cardAppointmentMiles));
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		String cardAppointment = format.format(date);
		String operateDate = request.getParameter("operateDate");
		String credentialNo = request.getParameter("credentialNo");
		logger.debug("applyType==>"+credential_type);
		logger.debug("cardNo==>"+cardNo);
		logger.debug("bussinessType==>"+bussinessType);
		logger.debug("cardType==>"+cardType);
		logger.debug("branchNo==>"+branchNo);
		logger.debug("opeatorNo==>"+opeatorNo);
		logger.debug("cardAppointment==>"+cardAppointment);
		logger.debug("operateDate==>"+operateDate);
		logger.debug("credentialNo==>"+credentialNo);
		//2.页面需要打印的凭证的业务类型
		/*if("".equals(credential_type)||null==credential_type){
			logger.error("凭证参数为空！");
			//throw exception;
		}*/
		//cardNo，credential_type最好是在Session中保存，暂时在这里保存,或者再通用Map中保存
		/*cleanSession(request);
		request.getSession().setAttribute("cardNo", cardNo);
		request.getSession().setAttribute("credential_type", credential_type);
		*/
		
		workMap.put("cardNo", cardNo);
		workMap.put("credential_type", credential_type);
		workMap.put("bussinessType", bussinessType);
		workMap.put("cardType", cardType);
		workMap.put("branchNo", branchNo);
		workMap.put("opeatorNo", opeatorNo);
		workMap.put("cardAppointment", cardAppointment);
		workMap.put("operateDate", operateDate);
		workMap.put("credentialNo", credentialNo);
		
		request.getSession().removeAttribute("credential_type");
		request.getSession().removeAttribute("credentialNo");
		request.getSession().setAttribute("credential_type", credential_type);
		request.getSession().setAttribute("credentialNo", credentialNo);
		
		//String file_path = request.getPathInfo();
		//System.out.println("pdfEdit_param:"+credential_type);
		//System.out.println("file_path:"+file_path);
		TempletTicket tt = new TempletTicket();
		//根据模板生成打印凭证
		String path =  tt.createPDF(workMap,request);
		logger.debug("topdfview[{}]",path);
		/*将状态码，转发请求路径，对话框的ID都放入map中，返回前端*/
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("statusCode", "200");
		map.put("callbackType", "forward");
		map.put("forwardUrl", "printCredentials/pdfViewPage");
		map.put("dialogId", "certPrint");
		map.put("credential_type", credential_type);
//		map.put("path", path);
		request.getSession().setAttribute("cert_path", path);
		return map;
	}
	
	/**
	 * 预览请求
	 * @param request
	 * @return map
	 */
	@RequestMapping(value="/toStoragePdfView",method=RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> storagePdfEdit(HttpServletRequest request){
		
		logger.info("storagePdfEdit########start()");
		String storageNo = request.getParameter("storageNo");
		String credential_type = request.getParameter("applyType");
		//20181206 hgl 增加以下1行
		String credential_ipAdress = request.getParameter("ipAddress");
		logger.debug("接收到的出入库号==>"+storageNo);
		logger.debug("接收到的打印凭证==>"+credential_type);
		request.getSession().removeAttribute("cert_path");
		request.getSession().removeAttribute("credential_type");
		request.getSession().removeAttribute("credentialNo");
		request.getSession().removeAttribute("ipAddress");
		request.getSession().setAttribute("credential_type", credential_type);
		request.getSession().setAttribute("credentialNo", storageNo);
		request.getSession().setAttribute("ipAddress", credential_ipAdress);
		/*将状态码，转发请求路径，对话框的ID都放入map中，返回前端*/
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("statusCode", "200");
		map.put("callbackType", "forward");
		map.put("forwardUrl", "printCredentials/storagePdfViewPage");
		map.put("dialogId", credential_type);

		return map;
	}
	/**
	 * 预览请求
	 * @param request
	 * @return map
	 */
	@RequestMapping(value="/toReChargePdfView",method=RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> reChargePdfEdit(HttpServletRequest request){
		
		logger.info("reChargePdfEdit########start()");
		Cert cert=(Cert) request.getSession().getAttribute("cert");
		String recordNum=String.valueOf((Integer) request.getSession().getAttribute("recordNum"));
		String cardpName=(String) request.getSession().getAttribute("cardpName");
		request.getSession().removeAttribute("cert");
		request.getSession().removeAttribute("recordNum");
		request.getSession().removeAttribute("cardpName");
		String[]cardTypeCode={"0","标准卡","记名衍生卡","非记名衍生卡","记名定制卡"};
		String certNo = cert.getCertNo();
		String credential_type = (String) request.getSession().getAttribute("type");
		String businessTypeName=cert.getCertType();
		String cardType=cardTypeCode[Integer.parseInt(cert.getCardTypecode())];
		String net=cert.getBranch();
		String Operator=cert.getLastOperator();
		Date lastDate=cert.getLastDate();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		String date = formatter.format(lastDate);
		logger.debug("接收到的出入库号==>"+certNo);
		logger.debug("接收到的打印凭证==>"+credential_type);
		
		Map<String,Object> workMap = new HashMap<String,Object>();
	 
		logger.debug("credential_type==>"+credential_type);
		logger.debug("certNo==>"+certNo);
		logger.debug("businessTypeName==>"+businessTypeName);
		logger.debug("cardType==>"+cardType);
		logger.debug("net==>"+net);
		logger.debug("Operator==>"+Operator);
		logger.debug("date==>"+date);
		logger.debug("recordNum==>"+recordNum);
		logger.debug("corpName==>"+cert.getCorpName());
		logger.debug("cardpName==>"+cardpName);
		//logger.debug("transactionDate==>"+transactionDate);
		
		workMap.put("credentialNo", certNo);
		workMap.put("credential_type", credential_type);
		workMap.put("bussinessType", businessTypeName);
		workMap.put("cardType", cardType);
		workMap.put("branchNo", net);
		workMap.put("operatorNo", Operator);
		workMap.put("operateDate", date);
		workMap.put("recordNum", recordNum);
		workMap.put("corpName", cert.getCorpName());
		workMap.put("cardpName", cardpName);
		
		request.getSession().removeAttribute("credential_type");
		request.getSession().removeAttribute("credentialNo");
		request.getSession().setAttribute("credential_type", credential_type);
		request.getSession().setAttribute("credentialNo", certNo);
		
		//String file_path = request.getPathInfo();
		//System.out.println("pdfEdit_param:"+credential_type);
		//System.out.println("file_path:"+file_path);
		TempletTicket tt = new TempletTicket();
		//根据模板生成打印凭证
		String path = tt.createPDF(workMap,request);
		
		/*将状态码，转发请求路径，对话框的ID都放入map中，返回前端*/
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("statusCode", "200");
		map.put("callbackType", "forward");
		map.put("forwardUrl", "printCredentials/pdfViewPage");
		map.put("dialogId", credential_type);
		request.getSession().setAttribute("cert_path", path);
		//map.put(key, value);
		return map;
	}
	
	/**
	 * 预览请求
	 * @param request
	 * @return map
	 */
	@RequestMapping(value="/toHairpinPdfView",method=RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> hairpinPdfEdit(HttpServletRequest request){
		
		logger.info("hairpinPdfEdit########start()");
		VoucherVo vo=(VoucherVo) request.getSession().getAttribute("vo");
		request.getSession().removeAttribute("vo");
		String[]cardTypeCode={"0","标准卡","记名衍生卡","非记名衍生卡","记名定制卡"};
		String certNo = vo.getCertNo();
		String credential_type = (String) request.getSession().getAttribute("type");
		String businessTypeName=vo.getBusinessTypeName();
		String cardType = null;
		if(!"".equals(vo.getCardType())&&vo.getCardType()!=null){
			if(StringUtils.isNumeric(vo.getCardType())){
				cardType = cardTypeCode[Integer.parseInt(vo.getCardType())];
			}else{
				cardType = vo.getCardType();
			}
		}
		String oldCitizenCardNo =vo.getOldCitizenCardNo();
		String oldCitizenBalance=vo.getOldCitizenBalance();
		String newCitizenCardNo=vo.getNewCitizenCardNo();
		String newCitizenCardBalance =vo.getNewCitizenCardBalance();
		String net=vo.getNet();
		String Operator=vo.getOperator();
		String date=vo.getDate();
		String transactionDate=vo.getTransactionDate();
		String transactionAmount=vo.getTransactionAmount();
		String ariginalAmount=vo.getAriginalAmount();
		String currentAmount=vo.getCurrentAmount();
		String cardpName=vo.getCardpName();
		String feeBln=vo.getFeeBln();
		String corpName=vo.getCorpName();
		String ActualApplyPeopleCount=null;
		if(vo.getActualApplyPeopleCount() != null){
		 ActualApplyPeopleCount=vo.getActualApplyPeopleCount().toString();
		}
		String appFlag=vo.getAppFlag();
		logger.debug("接收到的出入库号==>"+certNo);
		logger.debug("接收到的打印凭证==>"+credential_type);
		
		Map<String,Object> workMap = new HashMap<String,Object>();
	 
		logger.debug("credential_type==>"+credential_type);
		logger.debug("certNo==>"+certNo);
		logger.debug("businessTypeName==>"+businessTypeName);
		logger.debug("cardType==>"+cardType);
		logger.debug("oldCitizenCardNo==>"+oldCitizenCardNo);
		logger.debug("oldCitizenBalance==>"+oldCitizenBalance);
		logger.debug("newCitizenCardNo==>"+newCitizenCardNo);
		logger.debug("newCitizenCardBalance==>"+newCitizenCardBalance);
		logger.debug("net==>"+net);
		logger.debug("Operator==>"+Operator);
		logger.debug("date==>"+date);
		logger.debug("transactionDate==>"+transactionDate);
		logger.debug("transactionAmount==>"+transactionAmount);
		logger.debug("ariginalAmount==>"+ariginalAmount);
		logger.debug("currentAmount==>"+currentAmount);
		logger.debug("cardpName==>"+cardpName);
		logger.debug("feeBln==>"+feeBln);
		logger.debug("corpName==>"+corpName);
		logger.debug("ActualApplyPeopleCount==>"+ActualApplyPeopleCount);
		logger.debug("appFlag==>"+appFlag);
		
		workMap.put("credentialNo", certNo);
		workMap.put("credential_type", credential_type);
		workMap.put("bussinessType", businessTypeName);
		workMap.put("cardType", cardType);
		workMap.put("cardNo", oldCitizenCardNo);
		workMap.put("oldCardNo", oldCitizenCardNo);
		workMap.put("oldCardBalance", oldCitizenBalance);
		workMap.put("newCardNo", newCitizenCardNo);
		workMap.put("newCardBalance", newCitizenCardBalance);
		workMap.put("branchNo", net);
		workMap.put("operatorNo", Operator);
		workMap.put("cardAppointment", transactionDate);
		workMap.put("operateDate", date);
		workMap.put("operateTime", transactionDate);
		workMap.put("transactionAmount", transactionAmount);
		workMap.put("ariginalAmount", ariginalAmount);
		workMap.put("currentAmount", currentAmount);
		workMap.put("cardpName", cardpName);
		workMap.put("feeBln", feeBln);
		workMap.put("corpName", corpName);
		workMap.put("recordNum", ActualApplyPeopleCount);
		workMap.put("appFlag", appFlag);
		
		request.getSession().removeAttribute("credential_type");
		request.getSession().removeAttribute("credentialNo");
		request.getSession().setAttribute("credential_type", credential_type);
		request.getSession().setAttribute("credentialNo", certNo);
		
		//String file_path = request.getPathInfo();
		//System.out.println("pdfEdit_param:"+credential_type);
		//System.out.println("file_path:"+file_path);
		TempletTicket tt = new TempletTicket();
		//根据模板生成打印凭证
		String path = tt.createPDF(workMap,request);
		/*将状态码，转发请求路径，对话框的ID都放入map中，返回前端*/
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("statusCode", "200");
		map.put("callbackType", "forward");
		map.put("forwardUrl", "printCredentials/pdfViewPage");
		map.put("dialogId", credential_type);
		request.getSession().setAttribute("cert_path", path);
		//map.put(key, value);
		return map;
	}
	
	@RequestMapping(value="/pdfViewPage",method=RequestMethod.POST)
    public String pdfView(){
		logger.debug("pdfView####start");
		return "pdfViewPage";
		
		//return "pdfView";
	}
	
	//20181206 hgl 增加以下4行
	@RequestMapping(value="/storagePdfViewPage",method=RequestMethod.POST)
    public String storagePdfView(){
		return "StoragePdfViewPage";
	}
	
	@RequestMapping(value="/getPDFInfo",method=RequestMethod.GET)
	@ResponseBody
    public Map<String, Object> pdfInfo(HttpServletRequest request){
	
		Map<String, Object> map=new HashMap<>();
		map.put("credential_type", request.getSession().getAttribute("credential_type"));
		map.put("credentialNo", request.getSession().getAttribute("credentialNo"));
		map.put("path", request.getSession().getAttribute("cert_path"));
		map.put("ticket", request.getSession().getAttribute("ticket"));
		//20181206 hgl 增加以下1行
		map.put("ipAddress", request.getSession().getAttribute("ipAddress"));
		logger.debug("pdfpz-path:[{}]",map.get("path"));
		request.getSession().removeAttribute("credential_type");
		request.getSession().removeAttribute("credentialNo");
		request.getSession().removeAttribute("ticket");
		//20181206 hgl 增加以下1行
		request.getSession().removeAttribute("ipAddress");
		return map;
		//return "pdfView";
	}
	
	@RequestMapping(value="printCredentialPDF",method=RequestMethod.POST)
    public void pdfCredential(HttpServletRequest request) throws Exception{
		logger.info("pdfCredential########start()");
		HttpSession session =  request.getSession();
		String root =session.getServletContext().getRealPath("/");
		String pdfName = request.getParameter("pdfName");
		String paperNo = request.getParameter("paperNo");
		String targetPath = root + PathContants.PROJECT_PATH_ENCLOSURE_IMPORTED+File.separator+paperNo;
		String targetFileName = pdfName+"_applicationRegister.pdf";
		/*String fileName = request.getParameter("fileName");
		logger.debug("fileName:"+fileName);
		if(logger.isDebugEnabled()){
			logger.debug("fileName:"+fileName);
		}
		
		
		
		//先从远程复制文件到本地
		RemoteFile remoteFile = new RemoteFile();
		remoteFile.RemoteFileCopy(fileName);
		
		
		//1.把PDF文档转换成image
		String PDFPath = "D:\\template\\";
		PDF2Image pdf2Img = new PDF2Image();
		String targetPath_Name = pdf2Img.PDF2Images(PDFPath,fileName);
				
		//这里是目标路径存放PDF和Image
		if(logger.isDebugEnabled()){
			logger.debug("targetFileName:"+targetPath_Name);
		}
		
		PrintPDFImage printAction = new PrintPDFImage();
		printAction.printPDFImage(targetPath_Name);*/
		JFileChooser fileChooser = new JFileChooser();//创建打印作业
		//int state = fileChooser.showOpenDialog(null);
		//if(state == fileChooser.APPROVE_OPTION){
		
		logger.debug("pdfPath:"+targetPath+targetFileName);
		File file = new File(targetPath+File.separator+targetFileName);//获取选择的文件
		//File file = fileChooser.getSelectedFile();//获取选择的文件
		//构建打印请求属性集
		HashPrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
		//设置打印格式，因为未确定类型，所以选择autosense
		DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
		//查找所有的可用的打印服务
		PrintService printService[] = PrintServiceLookup.lookupPrintServices(flavor, pras);
		//定位默认的打印服务
		PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
		//显示打印对话框
		PrintService service = ServiceUI.printDialog(null, 200, 200, printService,defaultService, flavor, pras);
		if(service != null){
		try {
		DocPrintJob job = service.createPrintJob();//创建打印作业
		FileInputStream fis = new FileInputStream(file);//构造待打印的文件流
		DocAttributeSet das = new HashDocAttributeSet();
		Doc doc = new SimpleDoc(fis, flavor, das);
		job.print(doc, pras);
		} catch (Exception e){
		e.printStackTrace();
		}
		
		}
		
		
		logger.info("pdfCredential########end()");
		//return "pdfView";
	}
	
	/**
	 * Clean session内容，防止数据有误
	 * @param request
	 */
	public static void cleanSession(HttpServletRequest request){
		Enumeration em = request.getSession().getAttributeNames();
		  while(em.hasMoreElements()){
		   request.getSession().removeAttribute(em.nextElement().toString());
		  }
	}

}
